package com.example;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "bymobile";
    private static final String DATABASE_TABLE = "numbers";
    private static final int DATABASE_VERSION = 1;


    public static final String KEY_CODE = "code";
    public static final String KEY_PHONE = "phone";
    public static final String KEY_PASS = "pass";
    public static final String KEY_ROWID = "_id";

    private SQLiteDatabase mDb;

    private static final String DATABASE_CREATE =
            "create table " + DATABASE_TABLE + " (" + KEY_ROWID + " integer primary key autoincrement, "
                    + KEY_CODE + " text not null, " + KEY_PHONE + " text not null, "
                    + KEY_PASS + " text not null);";

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        mDb = getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        onCreate(db);
    }

    public Cursor fetchAll() {

        return mDb.query(DATABASE_TABLE, new String[]{KEY_ROWID, KEY_CODE,
                KEY_PHONE, KEY_PASS}, null, null, null, null, null);
    }

    public long createRecord(String code, String phone, String pass) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_CODE, code);
        initialValues.put(KEY_PHONE, phone);
        initialValues.put(KEY_PASS, pass);

        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }


    public Cursor fetchRecord(long rowId) throws SQLException {

        Cursor mCursor =

                mDb.query(true, DATABASE_TABLE, new String[]{KEY_ROWID,
                        KEY_CODE, KEY_PHONE, KEY_PASS}, KEY_ROWID + "=" + rowId, null,
                        null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }
}
